package com.ssm.socket;


import org.springframework.stereotype.Component;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

@Component
public class SocketModel {

    private ServerSocket serverSocket;



    public SocketModel() throws IOException {
         serverSocket = new ServerSocket(9000);
    }

    public void acceptData() {

        while (true) {
            try {
                Socket server = serverSocket.accept();
                System.out.println("等待远程连接，端口号为：" + serverSocket.getLocalPort() + "...");
                System.out.println("远程主机地址：" + server.getRemoteSocketAddress());
                InputStream in = server.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(in);
                byte [] bytes = new byte[1024];
                StringBuilder sb = new StringBuilder();
                while (dataInputStream.read(bytes) != -1) {
                    sb.append(new String(bytes));
                }
                System.out.println(sb.toString());
            } catch (SocketTimeoutException s) {
                System.out.println("Socket timed out!");
                break;
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }
}
